package edu.jd.movieplatform.security.admin.impl;

import edu.jd.movieplatform.common.Utils;
import edu.jd.movieplatform.security.admin.Admin;
import edu.jd.movieplatform.security.admin.AdminService;
import edu.jd.movieplatform.security.admin.dao.AdminDao;
import edu.jd.movieplatform.security.admin.DelAdminDto;
import edu.jd.movieplatform.security.admin.AdminDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service //说明这是一个受spring容器管理的业务组件(Bean)
@Transactional //说明本类的所有方法都是事务性
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminDao adminDao;

    @Override
    public Map<String, Object> getAdminPage(AdminDto dto) {
        //对于仅有一条语句，并且直接返回结果，可以进一步简化
        Map<String, Object> page =Utils.getPage(dto, ()->adminDao.findAdminListByCondition(dto));

        return page;
    }

    @Override
    public void addAdmin(AdminDto dto) {
        Admin admin = getAdminById(dto.getM_id());
        if(admin != null){
            throw new RuntimeException("已存在相同账号的用户！");
        }
        dto.setM_status("admin");
        dto.setM_pwd(DEFAULT_PASSWORD);
        adminDao.insertAdmintoSYS(dto);
        adminDao.insertAdmintoMR(dto);
    }

    @Override
    public void updateAdmin(AdminDto dto) {
        adminDao.updateAdmin(dto);
    }



    @Override
    public void deleteAdmin(DelAdminDto[] delAdmin) {
        if(delAdmin==null){
            throw new RuntimeException("没有获得需要删除用户的账号！");
        }
        int cnt =findFeedBackByAdminIds(delAdmin);
        if(cnt>0){
            throw new RuntimeException("部分管理员参与了其他功能！");
        }
        adminDao.deleteAdmin(delAdmin);
    }

    @Override
    public int findFeedBackByAdminIds(DelAdminDto[] delAdmin){
        int cnt = adminDao.findFeedBackByAdminIds(delAdmin);
        return cnt;
    }

    @Override
    public Admin getAdminById(String m_id) {
        Admin admin = adminDao.findAdminById(m_id);
        return admin;
    }

    @Override
    public void deleteOneAdmin(String m_id) {
        int cnt =findAdminFeedBack(m_id);
        if(cnt>0){
            throw new RuntimeException("该管理员进行过操作（回复），无法删除！");
        }
        adminDao.deleteOneAdmin(m_id);
    }

    @Override
    public int findAdminFeedBack(String m_id){
        int cnt =adminDao.findFeedBackCountByAdmin(m_id);
        return cnt;
    }

}
